package cn.swust.score.controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; 
import org.springframework.web.bind.annotation.RestController; 
import cn.swust.score.basepojo.ResultResponse; 
import cn.swust.score.pojo.Rater;
import cn.swust.score.service.RaterService;
import io.swagger.annotations.ApiOperation; 
 
@RestController
public class LoginController { 
	
	@Autowired
	RaterService raterService;
	@Autowired
	private AuthenticationManager authenticationManager;
	@PostMapping("/login")
	public  ResultResponse<Object> login(String username, String password,HttpServletRequest request) { 
		try {  
			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
					password);
			Authentication authentication = authenticationManager.authenticate(authRequest);
			SecurityContextHolder.getContext().setAuthentication(authentication);
			HttpSession session = request.getSession();
			session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());

			Rater roter = raterService.getByName(username);
			 
			 return new ResultResponse<Object>(0, "OK",roter); 
		} catch (AuthenticationException ex) {
			ResultResponse<Object> info = new ResultResponse<Object>(-1, "username or password error!",null);
			return info;
		}
	} 
 
	@GetMapping("/current")
	@ApiOperation(value = "当前登录用户") 
	public ResultResponse<Rater> currentUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication != null) {
			return new ResultResponse<Rater>((Rater) authentication.getPrincipal());
		} else
			return new ResultResponse<Rater>(-1,"the user not login!",null);
	}
	
//	@GetMapping("/logout")
//	public ResultResponse<Object> logout(HttpServletRequest request, HttpServletResponse response) {
//	    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//	    if (auth != null){    
//	        new SecurityContextLogoutHandler().logout(request, response, auth);
//	    }
//	    return new ResultResponse<Object>(0,"OK", null);
//	}

}
